

//
//  OASocketMethed.m
//  LongOA
//
//  Created by 耿用强 on 15/7/5.
//  Copyright (c) 2015年 耿用强. All rights reserved.
//

#import "OASocketMethed.h"
#import "JSON.h"
@implementation OASocketMethed
{
    NSMutableData*_allData;
    
    int type_tag;
    
    BOOL _isCancel;
}
static OASocketMethed *sharedOASocketMethed=nil;
#pragma mark - 获取单例
+ (OASocketMethed*)sharedOASocketMethed{
    if (!sharedOASocketMethed) {
        @synchronized(self)
        {
            
            if (!sharedOASocketMethed)
            {
                sharedOASocketMethed = [[OASocketMethed alloc]init];
                
            }
        }
    }
    return sharedOASocketMethed;
}

+ (id)allocWithZone:(NSZone *)zone
{
    if (sharedOASocketMethed == nil)
    {
        @synchronized(self)
        {
            if (sharedOASocketMethed == nil)
            {
                sharedOASocketMethed = [super allocWithZone:zone];
            }
        }
    }
    return sharedOASocketMethed;
}

- (id)init
{
    if (self = [super init])
    {
//        [sharedOASocketMethed initSocket];
    }
    return self;
}
-(void)initSocket
{
    _allData=[[NSMutableData alloc]init];
    self.clientSocket = [[AsyncSocket alloc] initWithDelegate:self];
    [self.clientSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
    [self connectHost:[GolbalManager sharedManager].IPString port:[[GolbalManager sharedManager].PORTString integerValue]];
     [_clientSocket isConnected];
}

//连接socket服务器
- (void)connectHost:(NSString *)ip port:(NSUInteger)port
{
    if (![_clientSocket isConnected])
    {
        NSError *error = nil;
        [_clientSocket connectToHost:ip onPort:port withTimeout:-1 error:&error];
        if (error)
        {
            NSLog(@"connectToHost error %@",error);
            if (self.completBolck) {
                NSError*error=[NSError new];
                self.completBolck(nil,error);
            }
            [_clientSocket disconnect];
        }
    }
}


#pragma mark - AsyncSocketDelegate

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
   
//    switch (err.code) {
//        case 65:
//            _offType=SocketOfflineByIpError;
//            [Commend showAlert:@"无法连接"];
//            break;
//        default:
//            
//            break;
//    }
    if (err!=nil) {
        [Commend showAlert:@"连接失败"];

        if (_isCancel==NO) {
            if (_completBolck!=nil) {
                
                self.completBolck(nil,err);
            }
        }
    }
   
    NSLog(@"client willDisconnectWithError:%@",err);
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
//    [Commend showAlert:@"服务器断开"];
    if (_isCancel==NO) {
        if (self.completBolck) {
            NSError*error=[NSError new];
            self.completBolck(nil,error);
        }
    }
}

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
    NSLog(@"client didConnectToHost");
    //这是异步返回的连接成功，
    
    
//    fun = "GetToken"
//    json = "{}"
//    req = fun + json
//    data = 将req转成utf-8的二进制
//    len = data.length
//    network.writebyte(0x04)
//    network.writeint(len)
//    network.writedata(data)
//    network.writeshort(0)
//    完成
    [self.clientSocket writeData:[self flag] withTimeout:-1 tag:0];
    NSLog(@"send0");
//    
    NSData*jsondataLenth=[self intToByteArray:(int)_sendData.length];
    [self.clientSocket writeData:jsondataLenth withTimeout:-1 tag:0];
    NSLog(@"send0");
    [self.clientSocket writeData:_sendData withTimeout:-1 tag:0];
    NSLog(@"send0");
    [self.clientSocket writeData:[self x0] withTimeout:-1 tag:0];
    NSLog(@"send0");
    
//    NSMutableData*data=[[NSMutableData alloc]init];
//    [data appendData:[self flag]];
//    [data appendData:jsondataLenth];
//    [data appendData:_sendData];
//    [data appendData:[self x0]];
//    [self.clientSocket writeData:data withTimeout:-1 tag:0];
    
    [sock readDataWithTimeout:-1 tag:0];
    NSLog(@"read0");
//    [sock readDataWithTimeout:-1 tag:1];
//    NSLog(@"read1");
//    [sock readDataWithTimeout:-1 tag:2];
//    NSLog(@"read2");
//    [sock readDataWithTimeout:-1 tag:3];
//    NSLog(@"read3");
}

- (NSString *)dataToString:(NSData *)data
{
    return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}


- (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag
{
    NSLog(@"%li",partialLength);
    
}
#pragma mark - 获取数据
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"didReadData%li,%lu", tag, (unsigned long)data.length);
    [_allData appendData:data];
    int lengt=[self getLength:_allData];
    NSLog(@"all:%lu,lengt:%i", (unsigned long)_allData.length, lengt);
    if (_allData.length==lengt+5) {
        NSLog(@"allReady");
          NSError*error=nil;
        if (self.completBolck) {
        _isCancel=YES;
        self.completBolck(_allData,error);
        }
    }
    [sock readDataWithTimeout:-1 tag:0];
    NSLog(@"dread0");
//    [sock readDataWithTimeout:-1 tag:1];
//    NSLog(@"dread1");
//    [sock readDataWithTimeout:-1 tag:2];
//    NSLog(@"dread2");
//    [sock readDataWithTimeout:-1 tag:3];
//    NSLog(@"dread3");
}


- (void)writeData:(NSData*)data andTag:(int)tag back:(CompletionLoadHandle)block
{
    _isCancel=NO;
    type_tag=(int)tag;
//    if ([self.clientSocket isConnected]==NO) {
        [self initSocket];
//    }
    self.completBolck=block;
    self.sendData=data;
    NSLog(@"writeData");
//    [self.clientSocket writeData:0 withTimeout:-1 tag:0];
}

- (NSData*)x0
{
    Byte bytes[2];
    short command = 0;
    Byte  b=( Byte) 0xff&command;
    bytes[0]=0x00;
    bytes[1]=0x00;
    
    NSData *newData = [[NSData alloc] initWithBytes:bytes length:2];
    return newData;
}

- (NSData*)flag
{
    Byte bytes[1];
    bytes[0] = (Byte) 0x04;
    
    NSData *newData = [[NSData alloc] initWithBytes:bytes length:1];
    return newData;
}



- (NSData*)intToByteArray:(int)nVal
{
    Byte bytes[4];

    bytes[3] = (Byte) ((nVal >> 24) & 0xFF);
    bytes[2] = (Byte) ((nVal >> 16) & 0xFF);
    bytes[1] = (Byte) ((nVal >> 8) & 0xFF);
    bytes[0] = (Byte) (nVal & 0xFF);
    NSData *newData = [[NSData alloc] initWithBytes:bytes length:4];
    
    return newData;
}
-(void)dealloc
{
    
    
}

- (int)getLength:(NSData*)data
{
    Byte*bytes=(Byte *)[data bytes];
    Byte chi[4];
    for (int a=0; a<4; a++)
    {
        chi[a]=bytes[a];
    }
    NSData *chidata=[NSData dataWithBytes:chi length:4];
    int code;
    [chidata getBytes:&code length:4];
    return code;
}
@end
